package ext.tianma.project.relatedproduct;

import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import wt.doc.WTDocument;
import wt.fc.ObjectIdentifier;
import wt.fc.ObjectReference;
import wt.fc.PersistInfo;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.iba.definition.litedefinition.AttributeDefDefaultView;
import wt.iba.definition.service.IBADefinitionHelper;
import wt.iba.value.StringValue;
import wt.inf.container.WTContainer;
import wt.method.RemoteAccess;
import wt.projmgmt.admin.Project2;
import wt.query.ClassAttribute;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.query.SubSelectExpression;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.vc.config.LatestConfigSpec;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.FormResult;
import com.ptc.netmarkets.project.processor.CreatePROPLProjectFormProcessor;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.iba.IBAUtil;

public class CusCreateProjectFormProcessor extends CreatePROPLProjectFormProcessor implements RemoteAccess {
	private static final String CLASSNAME = CusCreateProjectFormProcessor.class.getName() ;
	
	@Override
	public FormResult doOperation(NmCommandBean nmcommandbean,
			List<ObjectBean> paramList) throws WTException {
		FormResult formResult = super.doOperation(nmcommandbean, paramList);

		Project2 project = getProject2FromObjectBeans( paramList );

		if( project != null ){
			try {
				String rfqNumber = (String) IBAUtil.getIBAValue( project , "partRFQNumber" );
				System.out.println( "Debug   获取到的rfq的IBA值:"+rfqNumber );
				if( ( rfqNumber != null ) && ( !rfqNumber.equals("") ) ){
					try {
						WTDocument rfqDoc = getWTDocumentByIBAValue( "partRFQNumber" , rfqNumber );
						
						System.out.println( "Debug   获取到的RFQ文档rfqDoc:"+rfqDoc );
						if( rfqDoc != null ){
							setProjectIBAValues( project,rfqDoc ) ;
						}
						
//						WTDocument rfqDoc = null;
//						
//						if( !RemoteMethodServer.ServerFlag ){
//							String method = "getWTDocumentByIBAValue";
//							
//							Object object = RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null,
//									        new Class[] { String.class ,String.class }, new Object[] { "partRFQNumber", rfqNumber } );
//							if( object != null && object instanceof WTDocument ){
//								rfqDoc = (WTDocument) object;
//							}
//							
//						}else{
//							rfqDoc = getWTDocumentByIBAValue( "partRFQNumber", rfqNumber );
//						}
						System.out.println( "Debug   partRFQNumber:"+rfqDoc );
						if( rfqDoc != null ){
							System.out.println( "Debug   partRFQNumber:"+rfqDoc );
							setProjectIBAValues( project,rfqDoc ) ;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}

		return formResult;
	}

	private Project2 getProject2FromObjectBeans(List<ObjectBean> paramList) throws WTException {
		Project2 project = null;
		
		ObjectBean objBean = getObjectBeanByType(paramList, WTContainer.class);
		 
		if( objBean != null ){
			Object obj = objBean.getObject() ;
			 
			if( obj != null && obj instanceof Project2 ){
				project = ( Project2 ) obj ;
			}
		}
		
		return project ;
	}
	
	public WTDocument getWTDocumentByIBAValue( String ibaName , String ibaValue ) throws Exception {
		WTDocument doc = null ;
		System.out.println( "Debug   getWTDocumentByIBAValue..." );
		QuerySpec qs = new QuerySpec(WTDocument.class);

		AttributeDefDefaultView addv = IBADefinitionHelper.service.getAttributeDefDefaultViewByPath(ibaName);
		
		if (addv == null){
			throw new Exception("未找到属性"+ibaName+"的定义！");
		}
		
		long ibaDefId = addv.getObjectID().getId();
		
		QuerySpec qsub = new QuerySpec();
		
		int index = qsub.appendClassList(StringValue.class, false);
		System.out.println( "Debug   getWTDocumentByIBAValue:"+index );
		ClassAttribute ca = new ClassAttribute(StringValue.class, 
			StringValue.IBAHOLDER_REFERENCE + "."
			+ ObjectReference.KEY + "." 
			+ ObjectIdentifier.ID);
		
		qsub.appendSelect(ca, new int[]{index}, false);
		
		qsub.appendWhere(new SearchCondition(StringValue.class, 
			StringValue.DEFINITION_REFERENCE + "."
			+ ObjectReference.KEY + "." 
			+ ObjectIdentifier.ID,
			SearchCondition.EQUAL, ibaDefId), new int[]{index});
		
		qsub.appendAnd();

		qsub.appendWhere(new SearchCondition(StringValue.class,
		StringValue.VALUE, SearchCondition.LIKE,
		ibaValue.toUpperCase()), 
		new int[]{0});

		SubSelectExpression sse = new SubSelectExpression(qsub);

		qs.appendWhere(new SearchCondition(new ClassAttribute(
			WTDocument.class, Persistable.PERSIST_INFO + "." 
			+ PersistInfo.OBJECT_IDENTIFIER + "."
			+ ObjectIdentifier.ID), SearchCondition.IN, sse), 
			new int[]{0});
			
		qs.appendAnd();
		qs.setAdvancedQueryEnabled(true);	
		qs = new LatestConfigSpec().appendSearchCriteria(qs);				
		QueryResult qr = PersistenceHelper.manager.find(qs);					
		System.out.println( "Debug    QueryResult:"+qr.size() );
		if( qr != null && qr.hasMoreElements()){
			Object obj = qr.nextElement();
			
			if(obj != null && obj instanceof WTDocument){
				doc = (WTDocument) obj ;
			}
		}
		
		return doc ;
	}
	
	private void setProjectIBAValues(Project2 project, WTDocument rfqDoc ) throws RemoteException, WTException{
//		if( isPassiveProject ( project ) ){
//
//		}else if( isAdvTechProject( project ) ){
//			
//		}else if( isConsumptionProject( project ) ){
//			
//		}else if( isProfessionProject( project ) ){
//			
//		}
		
		Map<String,String> projectAttributesMapping = ProjectAttributeMappingUtil.getInstance().getProjectAttributesMapping() ;
		
		Iterator<String> ite = projectAttributesMapping.keySet().iterator() ;
		
		Hashtable projectIbaTable = new Hashtable() ;
		
		while( ite.hasNext() ){
			String rfqIba = ite.next() ;
			
			String projectIba = projectAttributesMapping.get( rfqIba );
			
			Object rfqIbaValue = IBAUtil.getIBAValue( rfqDoc , rfqIba );
			
			if( rfqIbaValue != null ){
				
				projectIbaTable.put( projectIba , rfqIbaValue ) ;
			}
		}
		
		IBAUtil.forceSetIBAValues( project , projectIbaTable ) ;
	}
	
	
	
	private boolean isPassiveProject( Project2 project ){
		boolean isPassiveProject = false ;
		
		String softTypeInternalValue = getSoftTypeInternal( project ) ;
		
		if( softTypeInternalValue.contains(".PassiveProject") ){
			isPassiveProject = true ;
		}
		
		return isPassiveProject ;
	}
	
	private boolean isAdvTechProject( Project2 project ){
		boolean isAdvTechProject = false ;
		
		String softTypeInternalValue = getSoftTypeInternal( project ) ;
		
		if( softTypeInternalValue.contains(".AdvTechProject") ){
			isAdvTechProject = true ;
		}
		
		return isAdvTechProject ;
	}
	
	private boolean isConsumptionProject( Project2 project ){
		boolean isConsumptionProject = false ;
		
		String softTypeInternalValue = getSoftTypeInternal( project ) ;
		
		if( softTypeInternalValue.contains(".ConsumptionProject") ){
			isConsumptionProject = true ;
		}
		
		return isConsumptionProject ;
	}
	
	private boolean isProfessionProject( Project2 project ){
		boolean isProfessionProject = false ;
		
		String softTypeInternalValue = getSoftTypeInternal( project ) ;
		
		if( softTypeInternalValue.contains(".ProfessionProject") ){
			isProfessionProject = true ;
		}
		
		return isProfessionProject ;
	}
	
	/**
	 * 获取对象软类型的内部值
	 * 
	 * @param obj
	 * @return
	 */
	private static String getSoftTypeInternal( WTObject obj) {
		String internalName = "";
		
		if(obj!=null) {
			try {
				//获取完整的内部值
				internalName=ClientTypedUtility.getTypeIdentifier(obj).getTypename() ;
			} catch(WTException e) {
				e.printStackTrace() ;
			}
		}
		
		if( internalName == null ){
			internalName = "" ;
		}
		
		return internalName; 
	}
}
